<template>
  <div class="app-container">
    <el-form class="searchFormClass" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据抽取方式" prop="loadType" label-width="100px">
        <el-select v-model="queryParams.loadType" placeholder="请选择" clearable size="small" @change="handleQuery()">
          <el-option
            v-for="dict in dict.type.zd_load_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据采集源" prop="dsId" label-width="100px">
        <!--自定义下拉项-->
        <el-select v-model="queryParams.dsId" filterable clearable placeholder="请选择" @change="handleQuery()">
          <el-option
            v-for="item in selectDSourceList"
            :key="item.dsId"
            :label="item.dsName"
            :value="item.dsId">
            <span style="float:left;color:#001528;font-size:13px;margin-right:18px;">{{ item.dsName }}</span>
            <span style="float:right;">{{ item.dsType }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Hive数据库" prop="hiveDb" label-width="85px">
        <el-input
          v-model="queryParams.hiveDb"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="Hive表" prop="hiveTable" label-width="60px">
        <el-input
          v-model="queryParams.hiveTable"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dmpdatacollect:task:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dmpdatacollect:task:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dmpdatacollect:task:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dmpdatacollect:task:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @row-dblclick="showForm" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" width="50" align="center" prop="taskId"/>
      <el-table-column label="任务名称" align="center" prop="taskName" min-width="120"/>
      <el-table-column label="任务描述" align="center" prop="taskDesc" :show-overflow-tooltip="true"/>
      <el-table-column label="数据抽取方式" align="center" prop="loadType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zd_load_type" :value="scope.row.loadType"/>
        </template>
      </el-table-column>
      <el-table-column label="数据采集源类型" align="center" prop="dsType"/>
      <el-table-column label="数据采集连接名" align="center" prop="dsName"/>
      <el-table-column label="源数据查询语句" align="center" prop="selectSql" min-width="130" :show-overflow-tooltip="true"/>
      <el-table-column label="Hive连接" align="center" prop="hvcName"/>
      <el-table-column label="Hive数据库" align="center" prop="hiveDb" min-width="100"/>
      <el-table-column label="Hive表" align="center" prop="hiveTable" min-width="100"/>
      <el-table-column label="Hive表存储格式" align="center" prop="autocreateStoretype">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hivetab_storetype" :value="scope.row.autocreateStoretype"/>
        </template>
      </el-table-column>
      <el-table-column label="数据采集引擎" align="center" prop="compName"/>
      <el-table-column label="调度系统名称" align="center" prop="dolsName"/>
      <el-table-column label="是否分区表" align="center" prop="isParttable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isAutoaddHivecol"/>
        </template>
      </el-table-column>
      <el-table-column label="是否自动新增hive列" align="center" prop="isAutoaddHivecol" min-width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isAutoaddHivecol"/>
        </template>
      </el-table-column>
      <el-table-column label="是否自动创建表" align="center" prop="isAutocreatetable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isAutoaddHivecol"/>
        </template>
      </el-table-column>
      <el-table-column label="是否包含data_loadtime列" align="center" prop="isAddcolLoadtime" min-width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isAutoaddHivecol"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="140" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-reading"
            @click="executeTask(scope.row)"
          >执行
          </el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-money"
            @click="copyRow(scope.row)"
            v-hasPermi="['dmpdatacollect:task:copy']"
          >复制
          </el-button>
          <br>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dmpdatacollect:task:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dmpdatacollect:task:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据采集任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="950px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-tabs v-model="activeName" :tab-position="tabPosition">

          <el-tab-pane label="源数据信息" name="datasourceInfo">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称"/>
            </el-form-item>
            <el-form-item label="任务描述" prop="taskDesc">
              <el-input v-model="form.taskDesc" placeholder="请输入任务描述"/>
            </el-form-item>
            <el-form-item label="数据抽取方式" prop="loadType">
              <el-select v-model="form.loadType" placeholder="请选择数据抽取方式">
                <el-option
                  v-for="dict in dict.type.zd_load_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数据采集源" prop="dsId">
              <!--自定义下拉项-->
              <el-select v-model="form.dsId" filterable placeholder="请选择">
                <el-option
                  v-for="item in selectDSourceList"
                  :key="item.dsId"
                  :label="item.dsName"
                  :value="item.dsId">
                  <span style="float:left;color:#001528;font-size:13px;margin-right:18px;">{{ item.dsName }}</span>
                  <span style="float:right;">{{ item.dsType }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="源数据查询语句" prop="selectSql">
              <el-tooltip content="变量必须使用 #{ 和 } 括起来, 示例 #{paramName}" placement="top">
                <el-button><span style="color:blue;">语句插入变量规范</span></el-button>
              </el-tooltip>
              <el-input v-model="form.selectSql" type="textarea" :autosize="{minRows:6 }" placeholder="请输入内容"/>
            </el-form-item>
            <el-divider content-position="center">源数据查询语句-变量生成策略信息</el-divider>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDmpDcollectTaskVariablegen">
                  添加
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini"
                           @click="handleDeleteDmpDcollectTaskVariablegen">
                  删除
                </el-button>
              </el-col>
            </el-row>
            <el-table :data="dmpDcollectTaskVariablegenList" :row-class-name="rowDmpDcollectTaskVariablegenIndex"
                      @selection-change="handleDmpDcollectTaskVariablegenSelectionChange"
                      ref="dmpDcollectTaskVariablegen">
              <el-table-column type="selection" width="50" align="center"/>
              <el-table-column label="序号" align="center" prop="index" width="50"/>
              <el-table-column label="源数据查询语句中的变量（程序自动识别）" :render-header="tableHeaderAddRedMi" prop="variable">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.variable" :disabled="true" placeholder="请输入"/>
                </template>
              </el-table-column>
              <el-table-column label="变量值生成类型" :render-header="tableHeaderAddRedMi" prop="varGentype">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.varGentype" placeholder="请选择" @change="varTypeChange(scope.row)">
                    <el-option
                      v-for="dict in dict.type.selectsql_var_gentype"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="日期时间格式" prop="datetimeVarformat">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.datetimeVarformat" v-if="scope.row.varGentype=='datetime'?true:false"
                            placeholder="请输入"/>
                </template>
              </el-table-column>
              <el-table-column label="变量值" :render-header="tableHeaderAddRedMi" prop="varValue">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.varGentype=='datetime' ? false:true" v-model="scope.row.varValue"
                            placeholder="请输入"/>
                  <el-select v-if="scope.row.varGentype=='datetime' ? true:false" v-model="scope.row.varValue"
                             filterable placeholder="请选择">
                    <el-option
                      v-for="dict in dict.type.dc_sel_datetime"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="写入Hive配置" name="writeHiveConfig">
            <el-form-item label="Hive连接名称" prop="hvcId">
              <!--自定义下拉项-->
              <el-select v-model="form.hvcId" filterable placeholder="请选择">
                <el-option
                  v-for="item in selectHiveConfigList"
                  :key="item.hvcId"
                  :label="item.hvcName"
                  :value="item.hvcId">
                  <span style="float:left;color:#001528;font-size:13px;margin-right:18px;">{{ item.hvcName }}</span>
                  <span style="float:right;">{{ item.hvVersion }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="写入的Hive数据库" prop="hiveDb">
              <el-input v-model="form.hiveDb" placeholder="请输入"/>
            </el-form-item>
            <el-form-item label="写入的Hive表" prop="hiveTable">
              <el-input v-model="form.hiveTable" placeholder="请输入"/>
            </el-form-item>
            <el-form-item label="Hive表存储格式" prop="autocreateStoretype">
              <el-select v-model="form.autocreateStoretype" placeholder="请选择">
                <el-option
                  v-for="dict in dict.type.hivetab_storetype"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否自动创建表" prop="isAutocreatetable">
              <el-select v-model="form.isAutocreatetable" placeholder="请选择">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否包含data_loadtime列" prop="isAddcolLoadtime">
              <el-select v-model="form.isAddcolLoadtime" placeholder="请选择">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否自动新增hive列" prop="isAutoaddHivecol">
              <el-select v-model="form.isAutoaddHivecol" placeholder="请选择">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否分区表" prop="isParttable">
              <el-select v-model="form.isParttable" @change="isParttableChange" placeholder="请选择">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-divider content-position="center">分区值生成策略信息</el-divider>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDmpDcollectTaskPartvaluegen">
                  添加
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini"
                           @click="handleDeleteDmpDcollectTaskPartvaluegen">删除
                </el-button>
              </el-col>
            </el-row>
            <el-table :data="dmpDcollectTaskPartvaluegenList" :row-class-name="rowDmpDcollectTaskPartvaluegenIndex"
                      @selection-change="handleDmpDcollectTaskPartvaluegenSelectionChange"
                      ref="dmpDcollectTaskPartvaluegen">
              <el-table-column type="selection" width="50" align="center"/>
              <el-table-column label="序号" align="center" prop="index" width="50"/>
              <el-table-column label="分区字段" :render-header="tableHeaderAddRedMi" prop="partfield">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.partfield" placeholder="请输入"/>
                </template>
              </el-table-column>
              <el-table-column label="分区值生成类型" :render-header="tableHeaderAddRedMi" prop="partvalGentype" width="180">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.partvalGentype" placeholder="请选择分区值生成类型"
                             @change="partvalTypeChange(scope.row)">
                    <el-option
                      v-for="dict in dict.type.partval_gentype"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="日期时间格式" prop="datetimeFormat">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.datetimeFormat" v-if="scope.row.partvalGentype=='datetime'?true:false"
                            placeholder="请输入"/>
                </template>
              </el-table-column>
              <el-table-column label="分区值" :render-header="tableHeaderAddRedMi" prop="partval">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.partvalGentype=='datetime' ? false:true" v-model="scope.row.partval"
                            placeholder="请输入"/>
                  <el-select v-if="scope.row.partvalGentype=='datetime' ? true:false" v-model="scope.row.partval"
                             filterable placeholder="请选择">
                    <el-option
                      v-for="dict in dict.type.dc_sel_datetime"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="采集引擎配置" name="dcCompConfig">
            <el-form-item label="采集引擎" prop="compId">
              <!--自定义下拉项-->
              <el-select v-model="form.compId" filterable placeholder="请选择">
                <el-option
                  v-for="item in selectDCCompList"
                  :key="item.compId"
                  :label="item.compName"
                  :value="item.compId">
                  <span style="float:left;color:#001528;font-size:13px;margin-right:18px;">{{ item.compName }}</span>
                  <span style="float:right;">{{ item.compVersion }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="调度配置" name="schedulerConfig">
            <el-form-item label="调度系统" prop="dolsId">
              <!--自定义下拉项-->
              <el-select v-model="form.dolsId" filterable clearable placeholder="请选择">
                <el-option
                  v-for="item in selectDolSdrList"
                  :key="item.dolsId"
                  :label="item.dolsName"
                  :value="item.dolsId">
                  <span style="float:left;color:#001528;font-size:13px;margin-right:18px;">{{ item.dolsName }}</span>
                  <span style="float:right;">{{ item.dolsVersion }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="isShowConfimBtn" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  .el-form-item {
    margin-bottom: 16px; /*控制行高*/
  }

  .searchFormClass .el-input {
    width: 150px;
  }
</style>

<script>
  import {
    listTask,
    getTask,
    delTask,
    addTask,
    updateTask,
    getSelectDSourceList,
    getHiveConfigList,
    copyTask,
    getDCCompList,
    getDolSdrList
  } from "@/api/dmpdatacollect/task";

  export default {
    name: "Task",
    dicts: ['zd_load_type', 'selectsql_var_gentype', 'hivetab_storetype', 'sys_yes_no', 'partval_gentype', 'dc_sel_datetime'],
    data() {
      return {
        // 日期时间下拉项
        datetimeValSelOptions: [],
        // 是否显示确定/提交按钮,默认true显示
        isShowConfimBtn: true,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedDmpDcollectTaskVariablegen: [],
        // 子表选中数据
        checkedDmpDcollectTaskPartvaluegen: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 数据采集任务表格数据
        taskList: [],
        // 源数据查询语句-变量生成策略表格数据
        dmpDcollectTaskVariablegenList: [],
        // 分区值生成策略表格数据
        dmpDcollectTaskPartvaluegenList: [],
        // 数据采集源下拉项数据，在created中初始化
        selectDSourceList: [],
        // Hive连接配置名下拉项数据，在created中初始化
        selectHiveConfigList: [],
        // 数据采集引擎下拉项数据，在created中初始化
        selectDCCompList: [],
        // 调度系统下拉项数据，在created中初始化
        selectDolSdrList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          taskName: null,
          loadType: null,
          dsId: null,
          hiveDb: null,
          hiveTable: null,
        },
        activeName: 'datasourceInfo',// tab默认激活的页签
        tabPosition: 'left',// tab方向
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          taskName: [
            {required: true, message: "任务名称不能为空", trigger: "blur"}
          ],
          loadType: [
            {required: true, message: "数据抽取方式不能为空", trigger: "change"}
          ],
          dsId: [
            {required: true, message: "数据采集源不能为空", trigger: "blur"}
          ],
          selectSql: [
            {required: true, message: "源数据查询语句不能为空", trigger: "blur"}
          ],
          hvcId: [
            {required: true, message: "Hive连接不能为空", trigger: "blur"}
          ],
          hiveDb: [
            {required: true, message: "写入的Hive数据库不能为空", trigger: "blur"}
          ],
          hiveTable: [
            {required: true, message: "写入的Hive表不能为空", trigger: "blur"}
          ],
          autocreateStoretype: [
            {required: true, message: "Hive表存储格式不能为空", trigger: "change"}
          ],
          isAutocreatetable: [
            {required: true, message: "是否自动创建表不能为空", trigger: "blur"}
          ],
          isAddcolLoadtime: [
            {required: true, message: "是否包含data_loadtime列不能为空", trigger: "blur"}
          ],
          isAutoaddHivecol: [
            {required: true, message: "是否自动新增hive列不能为空", trigger: "blur"}
          ],
          isParttable: [
            {required: true, message: "是否分区表不能为空", trigger: "blur"}
          ],
          compId: [
            {required: true, message: "采集引擎不能为空", trigger: "blur"}
          ],
          dolsId: [
            {required: true, message: "调度系统不能为空", trigger: "blur"}
          ],
          createTime: [
            {required: true, message: "创建日期不能为空", trigger: "blur"}
          ],
          updateTime: [
            {required: true, message: "更新时间不能为空", trigger: "blur"}
          ]
        }
      };
    },
    created() {
      this.getList();
      this.initDataSourceList();// 初始化数据采集源下拉项
      this.initHiveConfigList();// 初始化Hive连接配置名下拉项
      this.initDatetimeSelOptions();// 从字典中获取日期时间下拉项
      this.initDCCompList();// 初始化数据采集引擎下拉项
      this.initDolSdrList();// 初始化DS调度系统下拉项
    },
    methods: {
      // 表头添加红色*号
      tableHeaderAddRedMi(cerateElement, {column}) {
        return cerateElement("div", [
          cerateElement("span", column.label),
          cerateElement("span", {
            domProps: {
              innerHTML: "*"
            },
            style: {
              color: "red",
              fontSize: "16px",
              marginLeft: "5px"
            }
          })
        ]);
      },
      // 从字典中获取日期时间下拉项
      initDatetimeSelOptions() {
        this.getDicts('dc_sel_datetime').then(response => {
          var dictData = response.data;
          for (var i = 0; i < dictData.length; i++) {
            this.datetimeValSelOptions.push(dictData[i].dictValue);
          }
        });
      },
      //从后台获取数据采集源下拉项
      initDataSourceList() {
        getSelectDSourceList().then(response => {
          this.selectDSourceList = response.data;
        });
      },
      //从后台获取Hive连接配置名下拉项
      initHiveConfigList() {
        getHiveConfigList().then(response => {
          this.selectHiveConfigList = response.data;
        });
      },
      //从后台获取数据采集引擎下拉项
      initDCCompList() {
        getDCCompList().then(response => {
          this.selectDCCompList = response.data;
        });
      },
      //从后台获取调度系统下拉项
      initDolSdrList() {
        getDolSdrList().then(response => {
          this.selectDolSdrList = response.data;
        });
      },
      /** 查询数据采集任务列表 */
      getList() {
        this.loading = true;
        listTask(this.queryParams).then(response => {
          this.taskList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          taskId: null,
          taskName: null,
          taskDesc: null,
          loadType: null,
          dsId: null,
          selectSql: null,
          hvcId: null,
          hiveDb: null,
          hiveTable: null,
          autocreateStoretype: null,
          isAutocreatetable: null,
          isAddcolLoadtime: null,
          isAutoaddHivecol: null,
          isParttable: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.dmpDcollectTaskVariablegenList = [];
        this.dmpDcollectTaskPartvaluegenList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.taskId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加数据采集任务";
        // 设置默认值
        this.form = {
          autocreateStoretype: 'orc',
          isAutocreatetable: 'Y',
          isAddcolLoadtime: 'Y',
          isAutoaddHivecol: 'Y',
          isParttable: 'Y'
        };
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const taskId = row.taskId || this.ids
        getTask(taskId).then(response => {
          this.form = response.data;
          this.dmpDcollectTaskVariablegenList = response.data.dmpDcollectTaskVariablegenList;
          this.dmpDcollectTaskPartvaluegenList = response.data.dmpDcollectTaskPartvaluegenList;
          this.open = true;
          this.title = "修改数据采集任务";
          this.isShowConfimBtn = true;// 显示确定按钮
        });
      },
      /** 查看按钮操作 */
      showForm(row) {
        this.reset();
        const taskId = row.taskId || this.ids
        getTask(taskId).then(response => {
          this.form = response.data;
          this.dmpDcollectTaskVariablegenList = response.data.dmpDcollectTaskVariablegenList;
          this.dmpDcollectTaskPartvaluegenList = response.data.dmpDcollectTaskPartvaluegenList;
          this.open = true;
          this.title = "查看数据采集任务";
          this.isShowConfimBtn = false;// 隐藏确定按钮
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (!valid) {
            this.$modal.msgError("有内容未通过校验，请切换Tab查看!!");
          }else{
            this.form.dmpDcollectTaskVariablegenList = this.dmpDcollectTaskVariablegenList;
            this.form.dmpDcollectTaskPartvaluegenList = this.dmpDcollectTaskPartvaluegenList;

            // ---------------------------------------- 子表填写内容进行检验 ----------------------------------------
            //存放源数据查询语句中的变量
            let sqlVariableList = this.getSqlVariableList();
            //存放 源数据查询语句变量生成策略中的变量
            let variableGenList = this.getVariableGenList();
            let isShowVariableWarning = false;// 是否需要告警提示

            if (sqlVariableList.length != variableGenList.length) {
              isShowVariableWarning = true;
            } else {
              for (var i = 0; i < sqlVariableList.length; i++) {
                let varItem = sqlVariableList[i];
                if (variableGenList.indexOf(varItem) == -1) {
                  isShowVariableWarning = true;
                }
              }
            }
            if (isShowVariableWarning) {
              let warnStr = "源数据查询语句中的变量 " + sqlVariableList + " 与变量生成策略中的变量 " + variableGenList + " 不一致，请核对！！";
              this.$alert(warnStr, '提示', {
                type: "error",
                confirmButtonText: '确定'
              });
              return;
            }

            var variablegenLen = this.dmpDcollectTaskVariablegenList.length
            for (var i = 0; i < variablegenLen; i++) {
              var variable = this.dmpDcollectTaskVariablegenList[i].variable.trim();
              var varGentype = this.dmpDcollectTaskVariablegenList[i].varGentype.trim();
              var datetimeVarformat = this.dmpDcollectTaskVariablegenList[i].datetimeVarformat.trim();
              var varValue = this.dmpDcollectTaskVariablegenList[i].varValue.trim();
              if (variable.length == 0 || varGentype.length == 0 || varValue.length == 0) {
                this.$alert('变量生成策略信息 有必填项未填写，请核对!!', '提示', {
                  type: "error",
                  confirmButtonText: '确定'
                });
                return;
              }
              if ("datetime" == varGentype) {
                if (datetimeVarformat.length == 0) {
                  this.$alert("变量生成策略信息 变量值 "+variable+" 生成类型为日期时间，必须填写日期时间格式!!", '提示', {
                    type: "error",
                    confirmButtonText: '确定'
                  });
                  return;
                }
                if (this.datetimeValSelOptions.indexOf(varValue) == -1) {
                  this.$alert("变量生成策略信息 变量值 "+variable+" 生成类型为日期时间，变量值不合法 请重新选择", '提示', {
                    type: "error",
                    confirmButtonText: '确定'
                  });
                  return;
                }
              }
            }


            // ---------------------------------------- 子表填写内容进行检验 ----------------------------------------
            var partvaluegenLen = this.dmpDcollectTaskPartvaluegenList.length
            for (var i = 0; i < partvaluegenLen; i++) {
              var partfield = this.dmpDcollectTaskPartvaluegenList[i].partfield.trim();
              var partvalGentype = this.dmpDcollectTaskPartvaluegenList[i].partvalGentype.trim();
              var datetimeFormatStr = this.dmpDcollectTaskPartvaluegenList[i].datetimeFormat.trim();
              var partval = this.dmpDcollectTaskPartvaluegenList[i].partval.trim();

              if (partfield.length == 0 || partvalGentype.length == 0 || partval.length == 0) {
                this.$alert('分区值生成策略信息 有必填项未填写，请核对!!', '提示', {
                  type: "error",
                  onfirmButtonText: '确定'
                });
                return;
              }
              if ("datetime" == partvalGentype) {
                if(datetimeFormatStr.length == 0){
                  this.$alert("分区值生成策略信息 分区字段 "+partfield+" 生成类型为日期时间，必须填写日期时间格式!!", '提示', {
                    type: "error",
                    confirmButtonText: '确定'
                  });
                  return;
                }
                if (this.datetimeValSelOptions.indexOf(partval) == -1) {
                  this.$alert("分区值生成策略信息 分区字段 "+partfield+" 生成类型为日期时间，分区值 "+partval+" 不合法 请重新选择!!", '提示', {
                    type: "error",
                    confirmButtonText: '确定'
                  });
                  return;
                }
              }
              if (partvalGentype == "fromsqlvar" && sqlVariableList.indexOf(partval) == -1) {
                let warnStr = "分区值生成策略信息 分区字段 " + partfield + " 的分区值 " + partval + " 并不来自查询语句变量 " + sqlVariableList
                this.$alert(warnStr, '提示', {
                  type: "error",
                  confirmButtonText: '确定'
                });
                return;
              }
            }

            if (this.form.taskId != null) {
              updateTask(this.form).then(response => {
                if(response.data == -1){
                  this.$alert(response.msg, '提示', {
                    type: "error",
                    confirmButtonText: '确定'
                  });
                }else{
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addTask(this.form).then(response => {
                if(response.data == -1){
                  this.$alert(response.msg, '提示', {
                    type: "error",
                    confirmButtonText: '确定'
                  });
                }else{
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const taskIds = row.taskId || this.ids;
        this.$modal.confirm('是否确认删除数据采集任务编号为"' + taskIds + '"的数据项？').then(function () {
          return delTask(taskIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 复制按钮操作 */
      copyRow(row) {
        const taskId = row.taskId;
        const taskName = row.taskName;
        this.$modal.confirm('是否复制 ' + taskName + " 任务？").then(function () {
          return copyTask(taskId);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("复制成功");
        }).catch(() => {
        });
      },

      /** 源数据查询语句-变量生成策略序号 */
      rowDmpDcollectTaskVariablegenIndex({row, rowIndex}) {
        row.index = rowIndex + 1;
      },
      /** 源数据查询语句-变量生成策略添加按钮操作 */
      handleAddDmpDcollectTaskVariablegen() {
        //存放源数据查询语句中的变量
        let sqlVariableList = this.getSqlVariableList();

        //存放 源数据查询语句变量生成策略中的变量
        let variableGenList = this.getVariableGenList();

        // 待添加的变量
        let waitAddVariablegenList = [];
        for (var i = 0; i < sqlVariableList.length; i++) {
          let item = sqlVariableList[i];
          if (variableGenList.indexOf(item) == -1) {// 不包含
            waitAddVariablegenList.push(item);
          }
        }

        if (waitAddVariablegenList.length == 0) {
          this.$modal.msgError("源数据查询语句 中没有可添加的变量了!!");
        } else {
          for (var i = 0; i < waitAddVariablegenList.length; i++) {
            let itemVar = waitAddVariablegenList[i];

            // 创建一条变量生成策略
            let obj = {};
            obj.variable = itemVar;
            obj.varGentype = "";
            obj.datetimeVarformat = "";
            obj.varValue = "";
            this.dmpDcollectTaskVariablegenList.push(obj);
          }
        }
      },
      /** 源数据查询语句-变量生成策略删除按钮操作 */
      handleDeleteDmpDcollectTaskVariablegen() {
        if (this.checkedDmpDcollectTaskVariablegen.length == 0) {
          this.$modal.msgError("请先选择要删除的源数据查询语句-变量生成策略数据");
        } else {
          const dmpDcollectTaskVariablegenList = this.dmpDcollectTaskVariablegenList;
          const checkedDmpDcollectTaskVariablegen = this.checkedDmpDcollectTaskVariablegen;
          this.dmpDcollectTaskVariablegenList = dmpDcollectTaskVariablegenList.filter(function (item) {
            return checkedDmpDcollectTaskVariablegen.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleDmpDcollectTaskVariablegenSelectionChange(selection) {
        this.checkedDmpDcollectTaskVariablegen = selection.map(item => item.index)
      },

      /** 分区值生成策略序号 */
      rowDmpDcollectTaskPartvaluegenIndex({row, rowIndex}) {
        row.index = rowIndex + 1;
      },
      /** 分区值生成策略添加按钮操作 */
      handleAddDmpDcollectTaskPartvaluegen() {
        var isParttable = this.form.isParttable;
        if ('Y' != isParttable) {
          this.$modal.msgError("是否分区表为是 才能添加分区值生成策略");
          return;
        }
        let obj = {};
        obj.partfield = "";
        obj.partvalGentype = "";
        obj.datetimeFormat = "";
        obj.partval = "";
        this.dmpDcollectTaskPartvaluegenList.push(obj);
      },
      /** 分区值生成策略删除按钮操作 */
      handleDeleteDmpDcollectTaskPartvaluegen() {
        if (this.checkedDmpDcollectTaskPartvaluegen.length == 0) {
          this.$modal.msgError("请先选择要删除的分区值生成策略数据");
        } else {
          const dmpDcollectTaskPartvaluegenList = this.dmpDcollectTaskPartvaluegenList;
          const checkedDmpDcollectTaskPartvaluegen = this.checkedDmpDcollectTaskPartvaluegen;
          this.dmpDcollectTaskPartvaluegenList = dmpDcollectTaskPartvaluegenList.filter(function (item) {
            return checkedDmpDcollectTaskPartvaluegen.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleDmpDcollectTaskPartvaluegenSelectionChange(selection) {
        this.checkedDmpDcollectTaskPartvaluegen = selection.map(item => item.index)
      },

      /** 导出按钮操作 */
      handleExport() {
        this.download('dmpdatacollect/task/export', {
          ...this.queryParams
        }, `task_${new Date().getTime()}.xlsx`)
      },
      /** 变量值生成类型下拉项改变事件*/
      varTypeChange(row) {
        var index = row.index;
        var varGentype = row.varGentype;

        if ('datetime' != varGentype) {
          this.dmpDcollectTaskVariablegenList[index - 1].datetimeVarformat = "";// 日期时间格式 清空
        }
      },
      /** 分区值生成类型下拉项改变事件*/
      partvalTypeChange(row) {
        var index = row.index;
        var partvalGentype = row.partvalGentype;

        if ('datetime' != partvalGentype) {
          this.dmpDcollectTaskPartvaluegenList[index - 1].datetimeFormat = "";// 日期时间格式 清空
          this.dmpDcollectTaskPartvaluegenList[index - 1].partval = "";// 分区值 清空
        }
      },
      /** 是否分区表改变事件*/
      isParttableChange(val) {
        // 切换为不是分区表，并且有配置分区值生成策略，进行告警
        var partvaluegenListLen = this.dmpDcollectTaskPartvaluegenList.length
        if ('N' == val && partvaluegenListLen > 0) {
          this.$confirm('切换为不是分区表，将删除分区值生成策略, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.dmpDcollectTaskPartvaluegenList = []; // 清空内容
          }).catch(() => {
            // 点击了取消
            // 将是否分区表下列选中项恢复到是
            this.form.isParttable = 'Y'
          });
        }
      },
      // 获取源数据查询语句中的变量
      getSqlVariableList() {
        //存放源数据查询语句中的变量
        let sqlVariableList = [];
        let variableStartPrex = '#{' //变量以什么开头
        let sqlStr = this.form.selectSql;//源数据查询语句
        while (sqlStr.match(/#{(\S*)}/) != null) {
          let varName = sqlStr.match(/#{(\S*)}/)[0];
          if (varName == '#{}') {
            this.$modal.msgError("源数据查询语句 中 #{ 和 } 之间必须有变量名!!");
          }
          sqlVariableList.push(varName);
          let len = sqlStr.indexOf(variableStartPrex) + varName.length;
          sqlStr = sqlStr.substring(len);
        }
        return sqlVariableList;
      },
      // 获取源数据查询语句变量生成策略中的变量
      getVariableGenList() {
        //存放 源数据查询语句变量生成策略中的变量
        let variableGenList = [];
        let taskVariablegenListLen = this.dmpDcollectTaskVariablegenList.length
        if (taskVariablegenListLen > 0) {
          for (var i = 0; i < taskVariablegenListLen; i++) {
            variableGenList.push(this.dmpDcollectTaskVariablegenList[i].variable)
          }
        }
        return variableGenList;
      },


    }
  };
</script>
